package Thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/08/25
 * 线程同步--倒计时器
 */
public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        CountDownLatch countDownLatch = new CountDownLatch(3);

        Runnable task1 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算山西分公司的账目");
            /**
             * 每一个线程执行完，则这段代码会减去1
             */
            countDownLatch.countDown();
        };
        Runnable task2 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算北京分公司的账目");
            countDownLatch.countDown();
        };
        Runnable task3 = () -> {
            ThreadUtils.sleep(new Random().nextInt(5000));
            System.out.println("计算上海分公司的账目");
            countDownLatch.countDown();
        };
        pool.submit(task1);
        pool.submit(task2);
        pool.submit(task3);
        /**
         * 下面这段代码作用是：等待countDown的值减到0为止，才会去执行后面的代码
         */
        countDownLatch.await();
        System.out.println("计算总账！");
        pool.shutdown();
    }

}
